<?php
/* 
 SESSION.CLASS.PHP $ 2007/03/13 18:53:23 by martin
 It works with utils.php
 The use of cookie is essential in case of $sid==''
*/

#if(PHP_VERSION >= '5.1.0') date_default_timezone_set(TIMEZONE);

class Session {

 var $sid;
 var $dir;
 var $data;
 var $cache;

 function Session($sid=''){ # Constructor
  $this->sid = $sid;
  $this->data = array();
  $this->dir = OD;
  if(!$this->is_registered()){
   return FALSE; # anonymous
  } else return TRUE;  # session alive
 }
 
 function is_registered(){
  if($this->sid != ''){ // for non-cookie
   if(is_file($this->cache=$this->dir.'p2b_sess'.$this->sid)){
    if($this->decode()) return TRUE;
   }
   return FALSE;
  }
  if(!isset($_COOKIE['P2BSESSID'])){
   return FALSE;
  } else {
   foreach($_COOKIE['P2BSESSID'] as $key=>$val){
    if(is_file($this->cache=PATH.$this->dir.'p2b_sess'.$key)){ # PATH !!
     if($this->decode()){
      return TRUE;
     }
    }
   }
  }
  return FALSE;
 }

 function register(){ // create session cache file and cookie
  if(!empty($this->data['id'])){
   $this->cache = $this->dir.'p2b_sess'.$this->data['id'];
  } else return FALSE;
  if(!setcookie('P2BSESSID['.$this->data['id'].']', '1', 0) ){ # cookie can be set as array
   return FALSE;
  }
  if(!rewrite($this->cache, serialize($this->data))){
   return FALSE;
  }
  return TRUE;
 }

 function decode(){ // load session cache file and check its expire
  $this->data = unserialize(get_file_content($this->cache));
  if($this->data['expire'] < time()){
   $this->destroy();
   if(mt_rand(0, 100) < 50) $this->scavenge();
   return FALSE;
  }
  return TRUE;
 }
 
 function destroy(){ // delete cookie and session file
  $this->data = array();
  if(is_file($this->cache)) @unlink(realpath($this->cache));
  setcookie("P2BSESSID[$this->data['id']]", "", time()-60*60);
 }

 function scavenge(){ // delete old session files in the directory
  $sess = my_glob('p2b_sess', $this->dir);
  $now = time();
  if(is_array($sess)){
   foreach($sess as $t){
    $data = unserialize(get_file_content($t));
    if($data['expire'] < $now){
     @unlink(realpath($t));
     setcookie("P2BSESSID[".$data['id']."]", "", $now-60*60);
    }
   }
  }
 }
 
 function owner(){
  if(isset($this->data['ppBlog_login_name'])){
   return my_decrypt($this->data['ppBlog_login_name']);
  } else return ONAME;
 }
}

?>
